package models

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

type RequestToken struct {
	Id           int `json:"-"`
	Email        string
	Country      string
	Organization string
	Name         string
	Reg_key      string
	Reg_date     time.Time `orm:"auto_now_add;type(datetime)"`
}

func init() {
	orm.RegisterModel(new(RequestToken))
}

func AddRequestToken(token RequestToken) (string, error) {
	o := orm.NewOrm()
	o.Using("default")

	var atoken RequestToken
	err := o.QueryTable("RequestToken").Filter("email", token.Email).One(&atoken)
	if err == orm.ErrMultiRows {
		// 多条的时候报错
		fmt.Printf("Returned Multi Rows Not One")
		return "", errors.New("Multiple records exist.")
	}
	if err == orm.ErrNoRows {
		// 没有找到记录
		fmt.Printf("Not row found")
		hasher := md5.New()
		hasher.Write([]byte(token.Email))
		token.Reg_key = hex.EncodeToString(hasher.Sum(nil))
		o.Insert(&token)
		return token.Reg_key, nil
	}

	return atoken.Reg_key, nil
}

func GetAllRequestTokens() []*RequestToken {
	o := orm.NewOrm()
	var tokens []*RequestToken
	_, err := o.QueryTable("RequestToken").All(&tokens)
	if err != nil {
		return []*RequestToken{}
	}
	return tokens
}

func DeleteRequestToken(objectId int) {
	o := orm.NewOrm()
	if num, err := o.Delete(&RequestToken{Id: objectId}); err == nil {
		fmt.Println(num)
	}
}
